#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import config as c
from gitlab_map import site_map
import os
import re
import shutil
from glob import glob

root_path = c.local_www_path


def mycopyfile(srcfile, dstpath):
    fpath, fname = os.path.split(srcfile)             # 分离文件名和路径
    if not os.path.isfile(srcfile):
        print("%s not exist!" % (srcfile))
    else:
        fpath, fname = os.path.split(srcfile)             # 分离文件名和路径
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)                       # 创建路径
        shutil.copy(srcfile, dstpath + fname)          # 复制文件
        print("copy %s -> %s" % (srcfile, dstpath + fname))


def alter(file, new_str, pattern):
    try:
        with open(file, "r", encoding="utf-8") as f1, open("%s.bak" % file, "w", encoding="utf-8") as f2:
            content = f1.read()
            match_ret = re.search(pattern, content)
            flag = False
            if match_ret is None:
                print(file + ' ***** 异常: None,未匹配到 *****')
            else:
                text = re.sub(pattern, new_str, content)
                f2.write(text)
                flag = True

        if flag == True:
            os.remove(file)
            os.rename("%s.bak" % file, file)
            print(file + ' >>> 已完成')
    except Exception as e:
        print(file + ' ***** 异常 ***** >>> ' + str(e))

if __name__ == "__main__":
    for i in c.dirname_list:
        i = i.lower()
        dirname = site_map[i][35:][:-4].lower()
        project_path = root_path + dirname

        # src_dir = project_path + '/assets'        # /js/qtip/all
        # dst_dir = project_path + '/public/assets'       # 目的路径记得加斜杠
        # new_str = '''require dirname(__FILE__) . '/../common/common.inc.php';'''
        # pattern = "require[\ ]*dirname\(__FILE__\)\ *\.\ \'\/common\/common.inc.php\'\;"
        # shutil.copytree(src_dir, dst_dir)


        shutil.copy(project_path + '/common\helpers\SalesRuleHelper.php',
                    'G:/www/salesRuleHelper/' + dirname + '-SalesRuleHelper.php')    
        shutil.copy('G:/www/salesRuleHelper/SalesRuleHelper.php',
                    project_path + '/common\helpers\SalesRuleHelper.php')
        
        # alter(project_path + '/public/index.php', new_str, pattern)
        # src_file_list = glob(src_dir + '*')      # glob获得路径下所有/文件，可根据需要修改
        # for srcfile in src_file_list:
        #     shutil.copytree(srcfile, dst_dir)

        # for srcfile in src_file_list:
        #     mycopyfile(srcfile, dst_dir)         # 复制文件
